package client.comm.baoding.ui.vm

import android.app.Application
import android.content.Intent
import android.provider.Settings
import androidx.core.content.ContextCompat
import androidx.core.content.ContextCompat.startActivity
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import client.comm.commlib.ContextProvider
import client.comm.commlib.network.data.JsonResult
import client.comm.commlib.toast.toast
import client.comm.commlib.utils.SharedUtil
import client.comm.commlib.utils.StoreUtil
import client.comm.baoding.api.bean.Auth
import client.comm.baoding.ui.RegisterActivity
import client.comm.baoding.ui.WjmmActivity
import client.comm.baoding.ui.viewmodel.MiddleVm
import client.comm.baoding.api.bean.UserInfo
import client.comm.baoding.ui.TextContentActivity
import client.comm.baoding.utils.ReadAssetsUtil
import client.comm.commlib.App
import client.comm.commlib.comm_ui.WebActivity
import client.comm.commlib.network.HhRetroHttp
import client.comm.commlib.out_time
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import retrofit2.Response

class LoginViewModel(app: Application) : MiddleVm(app) {

    val auth = MutableLiveData<JsonResult<UserInfo>>()
    val account = MutableLiveData<String>()
    val password = MutableLiveData<String>()
    val isShowing = MutableLiveData<Boolean>(false)
    val isShowPwd = MutableLiveData<Boolean>(false)
    val isSelect = MutableLiveData<Boolean>(false)//是否选中

    fun switchIsShowPwd() {
        isShowPwd.value = !isShowPwd.value!!
    }

    fun switchSelectProtocol() {
        isSelect.value = !isSelect.value!!
    }

    fun clearAccount() {
        account.value = ""
    }

    /**
     * 登录
     */
    fun login() {
//        if (isSelect.value == false) {
//            toast("请您详细阅读并同意用户协议和隐私政策")
//            return
//        }
        if (account.value.isNullOrEmpty() || password.value.isNullOrEmpty()) {
            toast("账户和密码不能为空")
            return
        }
        viewModelScope.launch {
            isShowing.value = true
            flow {
                var emm: Response<JsonResult<Auth>>? = null
                out_time {
                    emm = server.login(
                        account.value!!, password.value!!, "android",
                        Settings.Secure.getString(
                            ContextProvider.get().activity!!.getContentResolver(),
                            Settings.Secure.ANDROID_ID,
                        ),
                        "${android.os.Build.BRAND + " " + android.os.Build.MODEL}"
                    )
                }
                emit(emm)
            }.map {
                var emm: JsonResult<UserInfo>? = JsonResult<UserInfo>().apply {
                    message = it?.body()?.message
                }
                it?.body()?.let {
                    if (it.isSuccess) {
                        SharedUtil.save("token", it.data!!.token)
                        out_time {
                            val call = server.userinfo().apply {
                                body()?.let {
                                    if (it.isSuccess) {
                                        StoreUtil.saveBean(getApplication(), it.data as UserInfo)
                                        SharedUtil.save("userState", it.data!!.status)
                                    }
                                }
                            }.body()
                            emm = call
                            if (call != null && call.isSuccess) {
                                StoreUtil.saveBean(getApplication(), call.data as UserInfo)
                                SharedUtil.save("userState", call.data!!.status)
                            }
                        }
                    }
                }
                emm
            }.flowOn(Dispatchers.IO).onCompletion { cause ->
                isShowing.value = false
            }.catch { cause ->
                if (cause != null) {
//                    toast(cause.message)
                    toast("网络错误")
                }
            }.collectLatest {
                auth.value = it
            }
        }

    }


    fun goRegister() {
        ContextProvider.get().activity?.apply {
            startActivity(Intent(this, RegisterActivity::class.java))
        }
    }

    fun goForgetPwd() {
        ContextProvider.get().activity?.apply {
            startActivity(Intent(this, WjmmActivity::class.java))
        }
    }


    fun user_protocol() {
        ContextProvider.get().activity?.apply {
            startActivity(
                Intent(this, TextContentActivity::class.java)
                    .putExtra("title", "用户协议")
                    .putExtra(
                        "content",
                        ReadAssetsUtil.getJson("userprotocol.txt", ContextProvider.get().activity)
                    )
            )
        }
    }

    fun privacy_policy() {
        ContextProvider.get().activity?.apply {
            startActivity(
                Intent(this, TextContentActivity::class.java)
                    .putExtra("title", "隐私政策")
                    .putExtra(
                        "content",
                        ReadAssetsUtil.getJson("agreement.txt", ContextProvider.get().activity)
                    )
            )
        }

//        ContextProvider.get().activity?.apply {
//                startActivity(
//                Intent(this, WebActivity::class.java)
//                    .putExtra("adInfo", "${HhRetroHttp.AGREEMENT}")//
//                    .putExtra("title", "隐私协议")
//            )
//        }


    }


}